package com.lagou.handler;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.mysql.jdbc.StringUtils;
import org.dom4j.Element;

import java.util.List;


public class MappedStatementBuilder {

    private Configuration configuration;

    private List<Element> elements;

    private String nodeType;

    private String namespace;

    public MappedStatementBuilder(Configuration configuration, List<Element> elements, String nodeType, String namespace) {
        this.configuration = configuration;
        this.elements = elements;
        this.nodeType = nodeType;
        this.namespace = namespace;
    }

    public void build() throws ClassNotFoundException {
        for (Element element : elements) {
            String id = element.attributeValue("id");
            String paramterType = element.attributeValue("paramterType");
            String resultType = element.attributeValue("resultType");
            Class<?> paramterTypeClass = getClassType(paramterType);
            Class<?> resultTypeClass = getClassType(resultType);
            String sqlText = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setNamespace(namespace);
            mappedStatement.setSqlId(id);
            mappedStatement.setSql(sqlText);
            mappedStatement.setParamterType(paramterTypeClass);
            mappedStatement.setResultType(resultTypeClass);
            mappedStatement.setNodeType(nodeType);
            this.configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
        }
    }

    public Class<?> getClassType(String classPath) throws ClassNotFoundException {
        if (StringUtils.isNullOrEmpty(classPath)) {
            return null;
        }
        return Class.forName(classPath);
    }
}
